<template>
  <div class="layout-padding-auto">
    <el-form :model="state.queryForm" ref="queryRef" :inline="true">
      <el-form-item :label="$t('inputoutput.mesProduceDate')" prop="inputDate">
        <div class="block">
          <el-date-picker v-model="inputDate" clearable type="daterange" unlink-panels range-separator="To"
                          start-placeholder="Start date" end-placeholder="End date" :shortcuts="shortcuts"  @change="handleDateChange" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" @click="query">{{ $t('so.query') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('so.reset') }}</el-button>
        <el-button type="success" icon="Download" plain @click="exportCard">{{ $t('inputOutputDetal.daochu') }}</el-button>
      </el-form-item>
<!--        <br />-->
<!--        <div style="margin: -5px 0  10px 0">-->
<!--          <span style="font-size: 14px;font-weight: 600;color: #303133">{{$t('inputOutputDetal.hgpSum')}}：{{ totalQualifiedQty||0 }}</span>-->
<!--          <span style="font-size: 14px;font-weight: 600;color: #303133;margin-left: 105px">{{$t('inputOutputDetal.cpSum')}}：{{ totalQty||0 }}</span>-->
<!--        </div>-->
    </el-form>
    <el-table v-loading="loading" :data="tableData" border style="width: 100%; height: 100%" :cell-style="tableStyle.cellStyle" stripe :header-cell-style="tableStyle.headerCellStyle" ref="tableRef" show-summary :summary-method="getSummaries">
      <el-table-column prop="date" :label="$t('inputoutput.mesProduceDate')" fixed width="120" align="center"/>
      <el-table-column v-for="process in processCodeOptions" :key="process.processCode" :label="process.processCode">
        <el-table-column :property="`${process.processCode}.qualified`" :label="$t('inputOutputDetal.qualified')" align="center" width="120">
          <template #default="scope">
            <el-tag type="success">
              {{ scope.row.outputData.find(item => item.processCode === process.processCode)?.qualified || '--' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :property="`${process.processCode}.defective`" :label="$t('inputOutputDetal.defective')" align="center" width="120">
          <template #default="scope">
            <el-tag type="danger">
              {{ scope.row.outputData.find(item => item.processCode === process.processCode)?.defective || '--' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :property="`${process.processCode}.rate`" :label="$t('inputOutputDetal.rate')" align="center" width="120">
          <template #default="scope">
            {{ scope.row.outputData.find(item => item.processCode === process.processCode)?.rate || '--' }}
          </template>
        </el-table-column>
        <el-table-column :property="`${process.processCode}.productLines`" :label="$t('inputOutputDetal.line')" align="center" width="150" show-overflow-tooltip>
          <template #default="scope">
            <el-tag type="success">
            {{ scope.row.outputData.find(item => item.processCode === process.processCode)?.productLines || '--' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :property="`${process.processCode}.hours`" :label="$t('inputOutputDetal.time')" align="center" width="150" show-overflow-tooltip>
          <template #default="scope">
            <el-tag type="warning">
              {{ scope.row.outputData.find(item => item.processCode === process.processCode)?.hours || '--' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    <pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" v-bind="state.pagination" />
  </div>
</template>
<script setup lang="ts">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus'
import {GetOutputRecordSum, GetOutputRecordSumTotalQty} from '/@/api/platform/report/inputoutput';



const { t } = useI18n();

const getYMD = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const today = new Date();
const endDate = new Date(today);
endDate.setDate(today.getDate());
today.setDate(today.getDate());
const inputDate = ref<[Date, Date] | null>([endDate, today]);
const queryRef = ref();
const tableRef = ref();
const loading = ref(false)
const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 限制日期选择范围，最多30天
const disabledDate = (time: Date) => {
  if (!inputDate.value || inputDate.value.length === 0 || inputDate.value.every(d => !d)) {
    return false;
  }
  const [start, end] = inputDate.value;
  // 只选了开始日期，限制结束日期只能选开始日期起30天内
  if (start && !end) {
    const max = new Date(start);
    max.setDate(max.getDate() + 30);
    return time.getTime() < start.getTime() || time.getTime() > max.getTime();
  }
  // 只选了结束日期，限制开始日期只能选结束日期前30天内
  if (!start && end) {
    const min = new Date(end);
    min.setDate(min.getDate() - 30);
    return time.getTime() > end.getTime() || time.getTime() < min.getTime();
  }
  // 都选了，限制区间在30天内
  if (start && end) {
    const max = new Date(start);
    max.setDate(max.getDate() + 30);
    return time.getTime() < start.getTime() || time.getTime() > max.getTime();
  }
  return false;
};

// 定义数据类型
interface ProcessData {
  processCode: string;
  productLines: string;
  qualified: number;
  defective: number;
  rate: string;
  hours: number;
}

interface TableRowData {
  date: string;
  outputData: ProcessData[];
}

// 表格数据
const tableData = ref<TableRowData[]>([]);
// 工序选项
const processCodeOptions = ref<Array<{ processCode: string }>>([]);
// 合计行数据
const totalRow = ref<Record<string, ProcessData>>({});
// 合计
const sumTotalList  = ref<any[]>([])

const state = reactive<BasicTableProps>({
  queryForm: {
    StartDate: inputDate.value ? getYMD(inputDate.value[0]) : '',
    EndDate: inputDate.value ? getYMD(inputDate.value[1]) : '',
  },
  pageList: GetOutputRecordSum,
  pagination: {
    total: 0,
    current: 1,
    pageSize: 20
  }
});

// 计算合计数据的方法
const calculateTotal = (data: TableRowData[]) => {
  // 初始化合计对象，为每个工序创建初始值
  const total: Record<string, ProcessData> = {};
  processCodeOptions.value.forEach(({ processCode }) => {
    total[processCode] = {
      processCode,
      qualified: 0,
      defective: 0,
      productLines: '0',
      rate: '0%',
      hours: 0
    };
  });

  // 遍历数据，累加每个工序的合格和不合格数量
  data.forEach(row => {
    row.outputData.forEach(item => {
      const processTotal = total[item.processCode];
      if (processTotal) {
        processTotal.qualified += Number(item.qualified);
        processTotal.defective += Number(item.defective);
      }
    });
  });

  // 计算每个工序的合格率
  Object.values(total).forEach(processTotal => {
    const totalPieces = processTotal.qualified + processTotal.defective;
    if (totalPieces > 0) {
      const rate = (processTotal.qualified / totalPieces) * 100;
      processTotal.rate = rate.toFixed(2) + '%';
    }
  });

  return total;
};

// 表格合计行方法
const getSummaries = (param: { columns: any[] }) => {
  const { columns } = param;
  const sums: string[] = [];

  columns.forEach((column, index) => {
    // 第一列显示"合计"
    if (index === 0) {
      sums[index] = t('inputOutputDetal.total');
      return;
    }

    // 获取工序代码和列类型
    const [processCode, columnType] = (column.property || '').split('.');

    // 查找对应工序的数据
    const processData = sumTotalList.value.find(item => item.processCode === processCode);

    // 如果找不到对应的工序数据，显示'-'
    if (!processCode || !processData) {
      sums[index] = '-';
      return;
    }

    // 根据列类型返回对应的值
    switch (columnType) {
      case 'qualified':
        sums[index] = processData.totalQualifiedQty.toString();
        break;
      case 'defective':
        sums[index] = processData.totalErrorQty.toString();
        break;
      case 'rate':
        const total = processData.totalQualifiedQty + processData.totalErrorQty;
        const rate = total > 0 ? (processData.totalQualifiedQty / total * 100).toFixed(2) + '%' : '0%';
        sums[index] = rate;
        break;
      case 'productLines':
          sums[index] = '--';
          break;
       case 'hours':
            sums[index] =processData.totalHours.toString();
         break;
      default:
        sums[index] = '--';
    }
  });

  return sums;
};

// 初始化数据
onMounted(() => {
  query();
});

// 查询方法
const query = () => {
  state.queryForm.StartDate = inputDate.value?.length > 0 ? getYMD(inputDate.value[0]) : '';
  state.queryForm.EndDate = inputDate.value?.length > 0 ? getYMD(inputDate.value[1]) : '';

  if(state.queryForm.StartDate == '' || state.queryForm.EndDate == '') return   ElMessage({
    message: t('inputOutputDetal.timeMsg'),
    type: 'warning',
    plain: true,
  })
  loading.value = true;
  // 获取总数统计
  GetOutputRecordSumTotalQty(state.queryForm).then((res) => {
    // totalQty.value = res.data.totalErrorQty;
    // totalQualifiedQty.value = res.data.totalQualifiedQty;
    sumTotalList.value = res.data;

  });

  // 获取表格数据
  GetOutputRecordSum({
    ...state.queryForm,
    current: state.pagination.current,
    size: state.pagination.pageSize
  }).then((res) => {
    if (res.data?.records) {
      tableData.value = res.data.records;
      state.pagination.total = res.data.total || 0;

      // 从返回的数据中提取所有唯一的 processCode
      // const uniqueProcessCodes = new Set<string>();
      // tableData.value.forEach(row => {
      //   row.outputData.forEach(item => {
      //     uniqueProcessCodes.add(item.processCode);
      //   });
      // });

      // 更新工序选项
      // processCodeOptions.value = Array.from(uniqueProcessCodes).sort().map(code => ({
      //   processCode: code
      // }));
      const processCodeList: string[] = [];
      tableData.value.forEach(row => {
        row.outputData.forEach(item => {
          if (!processCodeList.includes(item.processCode)) {
            processCodeList.push(item.processCode);
          }
        });
      });
      processCodeOptions.value = processCodeList.map(code => ({ processCode: code }));

      // 计算合计数据
      totalRow.value = calculateTotal(tableData.value);
      loading.value = false;
    }
  }).catch(() => {
    loading.value = false;
  });
};

// 重置查询
const resetQuery = () => {
  inputDate.value = null;
  const now = new Date();
  const startDate = new Date(now.getFullYear(), now.getMonth(), 1); // 本月开始日期
  const endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0); // 本月结束日期

  state.queryForm.StartDate = startDate.toISOString().split('T')[0]; // 格式化为 YYYY-MM-DD
  state.queryForm.EndDate = endDate.toISOString().split('T')[0]; // 格式化为 YYYY-MM-DD

  inputDate.value = [startDate,endDate];
  state.pagination.current = 1;
  query();
};

// 处理分页变化
const handleSizeChange = (val: number) => {
  state.pagination.current = 1;
  state.pagination.pageSize = val;
  query();
};

const handleCurrentChange = (val: number) => {
  state.pagination.current = val;
  query();
};

// 导出功能
const exportCard = () => {
  if (!inputDate.value || inputDate.value.length === 0)   return ElMessage({
    message: t('inputOutputDetal.timeMsg'),
    type: 'warning',
    plain: true,
  })
  downBlobFile('/wms/inputOutput/ExportProductOutput', {
    StartDate: inputDate.value?.length > 0 ? getYMD(inputDate.value[0]) : '',
    EndDate: inputDate.value?.length > 0 ? getYMD(inputDate.value[1]) : '',
  }, 'ProductOutput.xlsx');
};

// 获取表格相关方法
const { tableStyle, downBlobFile } = useTable(state);

// 日期区间变更校验
const handleDateChange = (val: [Date, Date] | null) => {
  if (val && val[0] && val[1]) {
    const diff = Math.abs(val[1].getTime() - val[0].getTime());
    const days = diff / (1000 * 60 * 60 * 24);
    if (days > 30) {
      inputDate.value = null;
      ElMessage.warning(t('inputOutputDetal.timeQJ'));
    }
  }
};
</script>
